import requests
import pandas as pd

jj_my = pd.read_excel(r'../Fund_form_files/JJ_bd.xlsx', dtype={'基金代码': str, '更新时间': str})

def get_fund_situation(fund_code, day):
    """获取基金最大回撤"""
    all_jz = []
    all_dates = []
    try:
        for i in range(day):
            # 请求数据
            url = f"http://api.fund.eastmoney.com/f10/lsjz?fundCode={fund_code}&pageIndex={i}&pageSize=20"
            headers = {'Referer': 'http://fundf10.eastmoney.com', 'User-Agent': 'Mozilla/5.0'}
            data = requests.get(url, headers=headers, timeout=10).json()
            # 提取净值数据并转换为浮点数
            for item in data['Data']['LSJZList']:
                if item['DWJZ']:
                    all_jz.insert(0, float(item['DWJZ']))
                    all_dates.insert(0, item['FSRQ'])
            # 计算最大回撤
        # print(len(all_jz),'条')
        max_dd = 0
        peak = all_jz[0]
        for value in all_jz:
            peak = max(peak, value)
            max_dd = max(max_dd, (peak - value) / peak * 100)
        print(f"{all_dates[0]}至{all_dates[-1]}\n"
              f"最大回撤:{max_dd:.2f}%\n最新净值:{all_jz[-1]:.4f}")
        return max_dd
    except Exception as e:
        print(f"{fund_code} 获取失败: {e}")
        return None


if __name__ == '__main__':
    # jj_num = jj_my['基金代码'].values
    # jj_name = jj_my['基金名称'].values
    jj_num = ["013478"]
    for fund in range(len(jj_num)):
        get_fund_situation(jj_num[fund], 12)
        print('=================================')
